<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>MongoDB拾遗(一) | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="MongoDB,">
  

  <meta name="description" content="一、环境搭建1.1 mongodb简介 MongoDB旨在为WEB应用提供可扩展的高性能数据存储解决方案 MongoDB 将数据存储为一个文档，数据结构由键值(key=&amp;gt;value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档，数组及文档数组   主要特点  高可扩展性 分布式存储 低成本 结构灵活  1.2 window下mongodb环境搭建 下载安装包或压">
<meta name="keywords" content="MongoDB">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB拾遗(一)">
<meta property="og:url" content="http://blog.poetries.top/2019/01/22/mongodb-review-1/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、环境搭建1.1 mongodb简介 MongoDB旨在为WEB应用提供可扩展的高性能数据存储解决方案 MongoDB 将数据存储为一个文档，数据结构由键值(key=&amp;gt;value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档，数组及文档数组   主要特点  高可扩展性 分布式存储 低成本 结构灵活  1.2 window下mongodb环境搭建 下载安装包或压">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://www.runoob.com/wp-content/uploads/2013/10/crud-annotated-document.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/182.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/183.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/12/184.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/349.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/350.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/351.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/352.png">
<meta property="og:image" content="http://www.runoob.com/wp-content/uploads/2013/10/Figure-1-Mapping-Table-to-Collection-1.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/353.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/2019/10/354.png">
<meta property="og:updated_time" content="2020-08-15T04:25:31.926Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MongoDB拾遗(一)">
<meta name="twitter:description" content="一、环境搭建1.1 mongodb简介 MongoDB旨在为WEB应用提供可扩展的高性能数据存储解决方案 MongoDB 将数据存储为一个文档，数据结构由键值(key=&amp;gt;value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档，数组及文档数组   主要特点  高可扩展性 分布式存储 低成本 结构灵活  1.2 window下mongodb环境搭建 下载安装包或压">
<meta name="twitter:image" content="http://www.runoob.com/wp-content/uploads/2013/10/crud-annotated-document.png">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#一、环境搭建"><span class="toc-text">一、环境搭建</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-1-mongodb简介"><span class="toc-text">1.1 mongodb简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-2-window下mongodb环境搭建"><span class="toc-text">1.2 window下mongodb环境搭建</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-3-linux下mongodb环境搭建"><span class="toc-text">1.3 linux下mongodb环境搭建</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#二、基本概念"><span class="toc-text">二、基本概念</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#2-1-数据库对比"><span class="toc-text">2.1 数据库对比</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-2-数据库"><span class="toc-text">2.2 数据库</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-3-文档"><span class="toc-text">2.3 文档</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-4-插入文档"><span class="toc-text">2.4 插入文档</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-5-插入数据表"><span class="toc-text">2.5 插入数据表</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#三、常用操作"><span class="toc-text">三、常用操作</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#3-1-创建用户"><span class="toc-text">3.1 创建用户</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-2-MongoDB-创建数据库"><span class="toc-text">3.2 MongoDB 创建数据库</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-3-MongoDB-删除数据库"><span class="toc-text">3.3 MongoDB 删除数据库</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-4-删除集合"><span class="toc-text">3.4 删除集合</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-5-MongoDB-插入文档"><span class="toc-text">3.5 MongoDB 插入文档</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-6-插入文档"><span class="toc-text">3.6 插入文档</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-7-MongoDB-更新文档"><span class="toc-text">3.7 MongoDB 更新文档</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-7-update-方法"><span class="toc-text">3.7 update() 方法</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#四、常用查询语句"><span class="toc-text">四、常用查询语句</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#五、MongoDB链接"><span class="toc-text">五、MongoDB链接</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#5-1-MongoDB链接express"><span class="toc-text">5.1 MongoDB链接express</span></a></li></ol></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-mongodb-review-1" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">MongoDB拾遗(一)</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2019.01.22</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/DataBase/">DataBase</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 2k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 8分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h1 id="一、环境搭建"><a href="#一、环境搭建" class="headerlink" title="一、环境搭建"></a>一、环境搭建</h1><h2 id="1-1-mongodb简介"><a href="#1-1-mongodb简介" class="headerlink" title="1.1 mongodb简介"></a>1.1 mongodb简介</h2><ul>
<li><code>MongoDB</code>旨在为WEB应用提供可扩展的高性能数据存储解决方案</li>
<li><code>MongoDB</code> 将数据存储为一个文档，数据结构由键值(<code>key=&gt;value</code>)对组成。<code>MongoDB</code> 文档类似于 <code>JSON</code> 对象。字段值可以包含其他文档，数组及文档数组</li>
</ul>
<p><img src="http://www.runoob.com/wp-content/uploads/2013/10/crud-annotated-document.png" alt></p>
<p><strong>主要特点</strong></p>
<ul>
<li>高可扩展性</li>
<li>分布式存储</li>
<li>低成本</li>
<li>结构灵活</li>
</ul>
<h2 id="1-2-window下mongodb环境搭建"><a href="#1-2-window下mongodb环境搭建" class="headerlink" title="1.2 window下mongodb环境搭建"></a>1.2 window下mongodb环境搭建</h2><ul>
<li>下载安装包或压缩包</li>
<li>添加<code>db</code>存储和日志存储文件夹</li>
<li>添加服务、配置环境变量、启动<code>Mongo</code></li>
</ul>
<blockquote>
<p>配置演示</p>
</blockquote>
<ul>
<li>在任意目录创建几个文件夹</li>
</ul>
<p><img src="https://poetries1.gitee.io/img-repo/2019/12/182.png" alt><br><img src="https://poetries1.gitee.io/img-repo/2019/12/183.png" alt></p>
<p><strong>通过命令行启动服务</strong></p>
<blockquote>
<p>配置环境变量</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment">#  --dbpath指定数据存储位置</span></span><br><span class="line">C:\Program Files\MongoDB\Server\3.4\bin\mongod --dbpath d:\mongodb\data</span><br></pre></td></tr></table></figure>
<p><img src="https://poetries1.gitee.io/img-repo/2019/12/184.png" alt></p>
<p><strong>通配置启动服务</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 配置d:\mongodb\etc\mongodb.conf</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#数据库路径</span></span><br><span class="line">dbpath=d:\mongodb\data\</span><br><span class="line"></span><br><span class="line"><span class="comment">#日志输出文件路径</span></span><br><span class="line">logpath=d:\mongodb\logs\mongodb.log</span><br><span class="line"></span><br><span class="line"><span class="comment">#错误日志采用追加模式，配置这个选项后mongodb的日志会追加到现有的日志文件，而不是从新创建一个新文件</span></span><br><span class="line">logappend=<span class="literal">true</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#启用日志文件，默认启用</span></span><br><span class="line">journal=<span class="literal">true</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#这个选项可以过滤掉一些无用的日志信息，若需要调试使用请设置为false</span></span><br><span class="line">quiet=<span class="literal">true</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#端口号 默认为27017</span></span><br><span class="line">port=27017</span><br><span class="line"></span><br><span class="line"><span class="comment">#指定存储引擎（默认先不加此引擎，如果报错了，大家在加进去）</span></span><br><span class="line">storageEngine=mmapv1</span><br><span class="line"></span><br><span class="line"><span class="comment">#http配置 开启这个服务才可以在网页中访问 端口28017</span></span><br><span class="line">httpinterface=<span class="literal">true</span></span><br></pre></td></tr></table></figure>
<ul>
<li>启动方式 </li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">C:\Program Files\MongoDB\Server\3.4\bin\mongod --config d:\mongodb\data</span><br></pre></td></tr></table></figure>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/349.png" alt></p>
<p><strong>更加简洁的启动方式</strong></p>
<blockquote>
<p>安装到<code>window</code>的服务里面，打开Windows看一下</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">C:\Program Files\MongoDB\Server\3.4\bin\mongod --config d:\mongodb\data --install --serviceName &quot;MongoDB&quot;</span><br></pre></td></tr></table></figure>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/350.png" alt></p>
<p><strong>使用MongoVue连接数据库</strong></p>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/351.png" alt><br><img src="https://poetries1.gitee.io/img-repo/2019/10/352.png" alt></p>
<h2 id="1-3-linux下mongodb环境搭建"><a href="#1-3-linux下mongodb环境搭建" class="headerlink" title="1.3 linux下mongodb环境搭建"></a>1.3 linux下mongodb环境搭建</h2><ul>
<li>下载安装包或压缩包</li>
<li>添加<code>db</code>存储和日志存储文件夹</li>
<li>添加服务、配置环境变量、启动<code>Mongo</code></li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 远程登录服务器</span></span><br><span class="line">ssh root@123.142.25.365</span><br></pre></td></tr></table></figure>
<blockquote>
<p>上传本地的安装包</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 上传文件夹，传文件不需要r</span></span><br><span class="line">scp /mongodb/... -r root@123.142.25.365:/home</span><br><span class="line"></span><br><span class="line"><span class="comment"># 传到服务器的/home/</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 在指定的目录创建启动需要的文件</span></span><br><span class="line"></span><br><span class="line">$ <span class="built_in">cd</span> /home/</span><br><span class="line">$ mkdir etc logs data</span><br><span class="line">$ touch logs/mongodb.log etc/mongo.conf</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># /home/etc/mongo.conf配置</span></span><br><span class="line"></span><br><span class="line">dbpath=/home/mongodb/data</span><br><span class="line">logpath=/mongodb/logs/mongodb.log</span><br><span class="line">logappend=<span class="literal">true</span></span><br><span class="line">journal=<span class="literal">true</span></span><br><span class="line">quiet=<span class="literal">true</span></span><br><span class="line">port=2701</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 启动服务</span></span><br><span class="line">mongod -f /home/mongodb/etc/mongo.conf</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 创建软连接</span></span><br><span class="line"></span><br><span class="line">ln -s /home/mongodb/bin/mongo /usr/<span class="built_in">local</span>/bin/mongo</span><br><span class="line"></span><br><span class="line">ln -s /home/mongodb/bin/mongod /usr/<span class="built_in">local</span>/bin/mongod</span><br></pre></td></tr></table></figure>
<h1 id="二、基本概念"><a href="#二、基本概念" class="headerlink" title="二、基本概念"></a>二、基本概念</h1><h2 id="2-1-数据库对比"><a href="#2-1-数据库对比" class="headerlink" title="2.1 数据库对比"></a>2.1 数据库对比</h2><table>
<thead>
<tr>
<th>SQL术语/概念</th>
<th>MongoDB术语/概念</th>
<th>解析/说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>database</code></td>
<td><code>database</code></td>
<td>数据库</td>
</tr>
<tr>
<td><code>table</code></td>
<td><code>collection</code></td>
<td>数据表/集合</td>
</tr>
<tr>
<td><code>row</code></td>
<td><code>document</code></td>
<td>数据记录/文档</td>
</tr>
<tr>
<td><code>column</code></td>
<td><code>field</code></td>
<td>数据记录行/文档</td>
</tr>
<tr>
<td><code>index</code></td>
<td><code>index</code></td>
<td>索引</td>
</tr>
<tr>
<td><code>table</code></td>
<td><code>joins</code></td>
<td>表连接，<code>MongoDB</code>不支持</td>
</tr>
<tr>
<td><code>primary key</code></td>
<td><code>primary key</code></td>
<td>主键,<code>MongoDB</code>自动将<code>_id</code>字段设置为主键</td>
</tr>
</tbody>
</table>
<p><img src="http://www.runoob.com/wp-content/uploads/2013/10/Figure-1-Mapping-Table-to-Collection-1.png" alt></p>
<h2 id="2-2-数据库"><a href="#2-2-数据库" class="headerlink" title="2.2 数据库"></a>2.2 数据库</h2><ul>
<li>一个<code>mongodb</code>中可以建立多个数据库</li>
<li><code>MongoDB</code>的默认数据库为”<code>db</code>“，该数据库存储在<code>data</code>目录中</li>
<li><code>&quot;show dbs&quot;</code> 命令可以显示所有数据的列表</li>
<li>执行 <code>&quot;db&quot;</code> 命令可以显示当前数据库对象或集合</li>
<li><code>&quot;use&quot;</code>命令，可以连接到一个指定的数据库</li>
</ul>
<h2 id="2-3-文档"><a href="#2-3-文档" class="headerlink" title="2.3 文档"></a>2.3 文档</h2><ul>
<li>文档是一组键值(<code>key-value</code>)对(即<code>BSON</code>)</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">&#123;<span class="string">"site"</span>:<span class="string">"www.runoob.com"</span>, <span class="string">"name"</span>:<span class="string">"菜鸟教程"</span>&#125;</span><br></pre></td></tr></table></figure>
<h2 id="2-4-插入文档"><a href="#2-4-插入文档" class="headerlink" title="2.4 插入文档"></a>2.4 插入文档</h2><ul>
<li>切换数据库<ul>
<li><code>use</code> 数据库名(没有就创建)</li>
</ul>
</li>
<li><code>db.createCollection(&quot;user&quot;)</code><ul>
<li>创建集合相当于创建表名</li>
<li>或者这样创建<ul>
<li><code>db.user.inert({id:123})</code></li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="2-5-插入数据表"><a href="#2-5-插入数据表" class="headerlink" title="2.5 插入数据表"></a>2.5 插入数据表</h2><p><strong>1. 手动插入</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 切换创建数据库</span></span><br><span class="line">use demo </span><br><span class="line"></span><br><span class="line"><span class="comment"># goods相当于数据表</span></span><br><span class="line">db.goods.insert(&#123;<span class="string">"prodictId"</span>:<span class="string">"10001"</span>,<span class="string">"productName"</span>:<span class="string">"aaa"</span>,<span class="string">"slaePrice"</span>:246,<span class="string">"productImage"</span>:<span class="string">"1.jpg"</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 创建数据表，暂时不需插入数据</span></span><br><span class="line">db.createCollection(<span class="string">"goods"</span>)</span><br></pre></td></tr></table></figure>
<p><strong>2. 客户端插入</strong></p>
<blockquote>
<p>利用<code>mongodbVue</code>导入</p>
</blockquote>
<h1 id="三、常用操作"><a href="#三、常用操作" class="headerlink" title="三、常用操作"></a>三、常用操作</h1><h2 id="3-1-创建用户"><a href="#3-1-创建用户" class="headerlink" title="3.1 创建用户"></a>3.1 创建用户</h2><p><strong>1. 创建管理员</strong></p>
<ul>
<li>开启服务</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># --auth进行授权，需要认证才可以</span></span><br><span class="line">mongod -f d:/mongodb/etc/mongodb.conf --auth</span><br></pre></td></tr></table></figure>
<p><strong>2. 通过非授权的方式启动服务</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 创建admin数据库</span></span><br><span class="line">use admin </span><br><span class="line"></span><br><span class="line"><span class="comment"># 给admin数据库创建账号 </span></span><br><span class="line">db.createUser(&#123;user:<span class="string">"admin"</span>,<span class="built_in">pwd</span>:<span class="string">"admin"</span>,roles:[<span class="string">"root"</span>]&#125;) <span class="comment"># 3.4</span></span><br><span class="line">db.addUser <span class="comment"># 2.x</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 创建成功需要认证</span></span><br><span class="line">db.auth(<span class="string">"admin"</span>,<span class="string">"admin"</span>) <span class="comment"># 账号、密码</span></span><br></pre></td></tr></table></figure>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/353.png" alt></p>
<p><strong>3. 给使用的数据库添加用户</strong></p>
<ol>
<li>创建用户</li>
</ol>
<p><img src="https://poetries1.gitee.io/img-repo/2019/10/354.png" alt></p>
<ol start="2">
<li>然后在授权登录试一下</li>
</ol>
<h2 id="3-2-MongoDB-创建数据库"><a href="#3-2-MongoDB-创建数据库" class="headerlink" title="3.2 MongoDB 创建数据库"></a>3.2 MongoDB 创建数据库</h2><ul>
<li><code>MongoDB</code> 创建数据库的语法格式如下</li>
<li>如果数据库不存在，则创建数据库，否则切换到指定数据库</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">use DATABASE_NAME</span><br></pre></td></tr></table></figure>
<ul>
<li>查看所有数据库 <ul>
<li><code>show dbs</code></li>
</ul>
</li>
<li>我们刚创建的数据库 runoob 并不在数据库的列表中， 要显示它，我们需要向 runoob 数据库插入一些数据</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">&gt; db.runoob.insert(&#123;<span class="string">"name"</span>:<span class="string">"poetries"</span>&#125;)</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : 1 &#125;)</span><br><span class="line">&gt; show dbs</span><br></pre></td></tr></table></figure>
<h2 id="3-3-MongoDB-删除数据库"><a href="#3-3-MongoDB-删除数据库" class="headerlink" title="3.3 MongoDB 删除数据库"></a>3.3 MongoDB 删除数据库</h2><ul>
<li><code>MongoDB</code>删除数据库的语法格式如下</li>
<li>删除当前数据库，默认为 <code>test</code>，你可以使用 <code>db</code> 命令查看当前数据库名</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">db.dropDatabase()</span><br></pre></td></tr></table></figure>
<h2 id="3-4-删除集合"><a href="#3-4-删除集合" class="headerlink" title="3.4 删除集合"></a>3.4 删除集合</h2><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">db.collection.drop()</span><br></pre></td></tr></table></figure>
<h2 id="3-5-MongoDB-插入文档"><a href="#3-5-MongoDB-插入文档" class="headerlink" title="3.5 MongoDB 插入文档"></a>3.5 MongoDB 插入文档</h2><blockquote>
<p>文档的数据结构和<code>JSON</code>基本一样</p>
</blockquote>
<h2 id="3-6-插入文档"><a href="#3-6-插入文档" class="headerlink" title="3.6 插入文档"></a>3.6 插入文档</h2><ul>
<li><code>MongoDB</code> 使用 <code>insert()</code>或 <code>save()</code> 方法向集合中插入文档，语法如下</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">db.COLLECTION_NAME.insert(document)</span><br></pre></td></tr></table></figure>
<ul>
<li>以下文档可以存储在 <code>MongoDB</code> 的 <code>runoob</code>数据库 的 <code>col</code> 集合中</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">&gt;db.col.insert(&#123;title: <span class="string">'MongoDB 学习'</span>, </span><br><span class="line">    description: <span class="string">'MongoDB 是一个 Nosql 数据库'</span>,</span><br><span class="line">    by: <span class="string">'poetries'</span>,</span><br><span class="line">    url: <span class="string">'http://blog.poetries.top'</span>,</span><br><span class="line">    tags: [<span class="string">'mongodb'</span>, <span class="string">'database'</span>, <span class="string">'NoSQL'</span>],</span><br><span class="line">    likes: 100</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<ul>
<li><p>以上实例中 <code>col</code> 是我们的集合名，如果该集合不在该数据库中， <code>MongoDB</code> 会自动创建该集合并插入文档。</p>
</li>
<li><p>查看已插入文档</p>
</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">&gt; db.col.find()</span><br><span class="line">&gt; db.col.find().pretty() <span class="comment">#格式化方式查看</span></span><br></pre></td></tr></table></figure>
<h2 id="3-7-MongoDB-更新文档"><a href="#3-7-MongoDB-更新文档" class="headerlink" title="3.7 MongoDB 更新文档"></a>3.7 MongoDB 更新文档</h2><ul>
<li><code>MongoDB</code> 使用 <code>update()</code> 和 <code>save()</code> 方法来更新集合中的文档</li>
</ul>
<h2 id="3-7-update-方法"><a href="#3-7-update-方法" class="headerlink" title="3.7 update() 方法"></a>3.7 update() 方法</h2><blockquote>
<p><code>update()</code> 方法用于更新已存在的文档。语法格式如下</p>
</blockquote>
<ul>
<li>通过 <code>update()</code>方法来更新标题(<code>title</code>):</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">db.col.update(&#123;&apos;title&apos;:&apos;MongoDB 学习&apos;&#125;,&#123;$set:&#123;&apos;title&apos;:&apos;MongoDB&apos;&#125;&#125;)</span><br></pre></td></tr></table></figure>
<h1 id="四、常用查询语句"><a href="#四、常用查询语句" class="headerlink" title="四、常用查询语句"></a>四、常用查询语句</h1><table>
<thead>
<tr>
<th>mongo</th>
<th>sql</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>db.users.find()</code></td>
<td><code>select * from users</code></td>
<td>从<code>user</code>表中查询所有数据</td>
</tr>
<tr>
<td><code>db.users.find({“username” : “joe”, “age” : 27})</code></td>
<td><code>select * from users where “username” = “joe” and age = 27</code></td>
<td>查找<code>username = joe</code>且<code>age = 27</code>的人</td>
</tr>
<tr>
<td><code>db.users.find({}, {“username” : 1, “email” : 1})</code></td>
<td><code>select username, email from users</code></td>
<td>查找<code>username</code>,<code>email</code>这<code>2</code>个子项</td>
</tr>
<tr>
<td><code>db.users.find({“age” : {“$gt” : 18}})</code></td>
<td><code>select * from users where age &gt;18</code></td>
<td>查找<code>age &gt; 18</code>的会员</td>
</tr>
<tr>
<td><code>db.users.find({“age” : {“$gte” : 18}})</code></td>
<td><code>select * from users where age &gt;=18</code></td>
<td>查找<code>age &gt;= 18</code>的人</td>
</tr>
<tr>
<td><code>db.users.find({“age” : {“$lt” : 18}})</code></td>
<td><code>select * from users where age &lt;18</code></td>
<td>查找<code>age &lt; 18</code>的人</td>
</tr>
<tr>
<td><code>db.users.find({“age” : {“$lte” : 18}})</code></td>
<td><code>select * from users where age &lt;=18</code></td>
<td>查找<code>age &lt;= 18</code>的人</td>
</tr>
<tr>
<td><code>db.users.find({“username” : {“$ne” : “joe”}})</code></td>
<td><code>select * from users where username &lt;&gt; “joe”</code></td>
<td>查找 <code>username != joe</code>的会员</td>
</tr>
<tr>
<td><code>db.users.find({“ticket_no” : {“$in” : [725, 542, 390]}})</code></td>
<td><code>select * from users where ticket_no in (725, 542, 390)</code></td>
<td>符合<code>tickt_no</code>在此范围的结果</td>
</tr>
<tr>
<td><code>db.users.find({“ticket_no” : {“$nin” : [725, 542, 390]}})</code></td>
<td><code>select * from users where ticket_no not in (725, 542, 390)</code></td>
<td>符合<code>tickt_no</code>不在此范围的结果</td>
</tr>
<tr>
<td><code>db.users.find({“name” : /joey^/})</code></td>
<td><code>select * from users where name like “joey%”</code></td>
<td>查找前<code>4</code>个字符为<code>joey</code>的人</td>
</tr>
</tbody>
</table>
<h1 id="五、MongoDB链接"><a href="#五、MongoDB链接" class="headerlink" title="五、MongoDB链接"></a>五、MongoDB链接</h1><h2 id="5-1-MongoDB链接express"><a href="#5-1-MongoDB链接express" class="headerlink" title="5.1 MongoDB链接express"></a>5.1 MongoDB链接express</h2><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>);</span><br><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">'mongoose'</span>);</span><br><span class="line"><span class="keyword">const</span> app = express();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 连接mongo 并且使用React这个集合，没有就会新建</span></span><br><span class="line"><span class="keyword">const</span> DB_URL = <span class="string">'mongodb://127.0.0.1:27017/react'</span>;</span><br><span class="line">mongoose.connect(DB_URL);</span><br><span class="line">mongoose.connection.on(<span class="string">'connected'</span>,()=&gt;&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'mongo connect success'</span>);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 类似于MySQL的表 mongo里有文档、字段的概念</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> User = mongoose.model(<span class="string">'user'</span>,<span class="keyword">new</span> mongoose.Schema(&#123;</span><br><span class="line">    user:&#123;<span class="attr">type</span>:<span class="built_in">String</span>,<span class="attr">require</span>:<span class="literal">true</span>&#125;,</span><br><span class="line">    age:&#123;<span class="attr">type</span>:<span class="built_in">Number</span>,<span class="attr">require</span>:<span class="literal">true</span>&#125;</span><br><span class="line">&#125;))</span><br><span class="line"></span><br><span class="line"><span class="comment">//新增数据</span></span><br><span class="line"><span class="comment">// User.create(&#123;</span></span><br><span class="line"><span class="comment">//     user:'小胡',</span></span><br><span class="line"><span class="comment">//     age:18</span></span><br><span class="line"><span class="comment">// &#125;,(err,doc)=&gt;&#123;</span></span><br><span class="line"><span class="comment">//     if(!err) &#123;</span></span><br><span class="line"><span class="comment">//         console.log(doc)</span></span><br><span class="line"><span class="comment">//     &#125; else &#123;</span></span><br><span class="line"><span class="comment">//         console.log(err)</span></span><br><span class="line"><span class="comment">//     &#125;</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 删除数据 &#123;&#125;过滤对象</span></span><br><span class="line"><span class="comment">// User.remove(&#123;age:22&#125;,(err,doc)=&gt;&#123;</span></span><br><span class="line"><span class="comment">//     console.log(doc)</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"><span class="comment">// 更新</span></span><br><span class="line">User.update(&#123;<span class="string">'user'</span>:<span class="string">'小明'</span>&#125;,&#123;<span class="string">'$set'</span>:&#123;<span class="attr">age</span>:<span class="number">30</span>&#125;&#125;,(err,doc)=&gt;&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(doc)</span><br><span class="line">&#125;)</span><br><span class="line">app.get(<span class="string">'/'</span>,(req,res)=&gt;&#123;</span><br><span class="line">    res.send(<span class="string">'&lt;h1&gt;Hello word!&lt;/h1&gt;'</span>)</span><br><span class="line">&#125;)</span><br><span class="line">app.get(<span class="string">'/data'</span>,(req,res)=&gt;&#123;</span><br><span class="line">    <span class="comment">// findOne 只返回一条，返回对象直接使用，而不是返回数组</span></span><br><span class="line">    User.findOne(&#123;<span class="string">'user'</span>:<span class="string">'小明'</span>&#125;,(err,doc)=&gt;&#123;</span><br><span class="line">        res.json(doc)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">app.listen(<span class="number">9000</span>,()=&gt;&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'Node app listen 9000'</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2019/01/22/mysql-base-review/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2019/01/24/node-socketio/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
